﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : PhotonServerProject | PhotonServerCommon | SerializerHelper.cs
// //  Created : 2016 - 04 - 07 17:03
// //  Modified: 2016 - 04 - 18 09:38
// //  ********************************************************************************

using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace PhotonServerCommon
{
    public class SerializerHelper
    {
        public static string Serialize(object serObj)
        {
            DataContractSerializer dsc = new DataContractSerializer(serObj.GetType());
            StringBuilder sb = new StringBuilder();
            using (XmlWriter xw = XmlWriter.Create(sb))
            {
                dsc.WriteObject(xw, serObj);
            }
            return sb.ToString();
        }

        public static T DeSerialize<T>(string xmlString) where T : class
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof (T));

            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
            {
                return dcs.ReadObject(reader) as T;
            }
        }

        public static string SerializeXml(object serObject)
        {
            XmlSerializer xsSubmit = new XmlSerializer(serObject.GetType());
            StringWriter sww = new StringWriter();
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                xsSubmit.Serialize(writer, serObject);
                return sww.ToString();
            }
        }

        public static T DeSerializeXml<T>(string xmlString) where T : class
        {
            XmlSerializer xsInput = new XmlSerializer(typeof (T));
            StringReader str = new StringReader(xmlString);
            return xsInput.Deserialize(XmlReader.Create(str)) as T;
        }
    }
}
